package algorithm;

public class InsertSortByLinkedList {
    static class Node {
        int val;
        Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    static Node insertSort(Node head) {
        Node sentinel = new Node(-1, head);
        Node cur = sentinel.next;
        while (cur != null && cur.next!=null) {
            if (cur.val < cur.next.val) {
                cur = cur.next;
            } else {
                Node temp = cur.next;
                cur.next = cur.next.next;
                Node pre =sentinel;
                while(pre.next.val < temp.val){
                    pre = pre.next;
                }
                temp.next = pre.next;
                pre.next = temp;
            }
        }
        return sentinel.next;
    }

    public static void main(String[] args) {
        Node n1 = new Node(24,null);
        Node n2 = new Node(1,n1);
        Node n3 = new Node(3,n2);
        Node n4 = new Node (5,n3);
        Node n5 = new Node (33,n4);
        Node head = new Node(7,n5);
        Node p =head;
        while(p.next!=null){
            System.out.print(p.val+" ");
            p = p.next;
        }
        System.out.println("-------");
        Node head2 = insertSort(head);
        p =head2;
        while(p.next!=null){
            System.out.print(p.val+" ");
            p = p.next;
        }
    }
}
